//
//  CameraViewController.m
//  UILbrary
//
//  Created by mac on 16/12/24.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "CameraViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "UIFactory.h"
#import "EditImageVeiwControllerViewController.h"
@interface CameraViewController ()
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) UIView *preview;
@property (nonatomic, strong) AVCaptureStillImageOutput *imageOutput;
@end

@implementation CameraViewController




- (void)viewDidLoad {
    [super viewDidLoad];

    //Device
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    AVCaptureDevice *audioCatureDevice = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
    
    //input
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:nil];
    if ([self.session canAddInput:deviceInput]) {
        [self.session addInput:deviceInput];
    }
    //分辨率
    if ([self.session canSetSessionPreset:AVCaptureSessionPresetHigh]) {
        [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    }
    //初始化按钮
    [self p_configSubViews];
    
    //预览 session
    [self p_loadPreviewLayer];
    
    //output
    self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *setting = @{AVVideoCodecKey:AVVideoCodecJPEG};
//    NSDictionary *setting = [[NSDictionary alloc]initWithObjectsAndKeys:AVVideoCodecJPEG, AVVideoCodecKey, nil];
    self.imageOutput.outputSettings = setting;
    [self.session addOutput:self.imageOutput];

    [self.session startRunning];
}

- (void)p_configSubViews{
    [self.view addSubview:self.preview];
    
    //前后摄像头切换
    UIButton *swithCameraButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 100, 100, 30)];
    [swithCameraButton setTitle:@"切换摄像头" forState:UIControlStateNormal];
    [swithCameraButton addTarget:self action:@selector(swithCameraButtonMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:swithCameraButton];
    
    //拍照按钮
    UIButton *photographButton = [UIFactory buttonWithFrame:CGRectMake(0, 0, 40, 40) backgroundImageName:@"" imageName:@"" title:@"拍照" titleColor:[UIColor orangeColor]];
    photographButton.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2.0, [UIScreen mainScreen].bounds.size.height - 100);
    [photographButton addTarget:self action:@selector(p_photographButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:photographButton];
    
}

/**
 预览 session 拍照相框大小
 */
- (void)p_loadPreviewLayer{
    
    AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    
    CGFloat proportion = 1.0;
    previewLayer.frame = CGRectMake(100, 100, 200, 200);
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.preview.layer.masksToBounds = YES;
    [self.preview.layer insertSublayer:previewLayer atIndex:0];
}

- (void)p_presentEditViewController:(UIImage *)image{

    EditImageVeiwControllerViewController *editoImageVC = [EditImageVeiwControllerViewController new];
    editoImageVC.editoImageView.image = image;
    [self presentViewController:editoImageVC animated:YES completion:nil];
}

#pragma mark - event methods
//拍照事件
- (void)p_photographButton{
    
    //闪光效果
    UIView *flashView = [[UIView alloc] initWithFrame:self.preview.bounds];
    flashView.backgroundColor = [UIColor blackColor];
    [self.preview.window addSubview:flashView];
    
    [UIView animateWithDuration:.4f animations:^{
        flashView.alpha = .0f;
    } completion:^(BOOL finished) {
        [flashView removeFromSuperview];
    }];
    
    //获取相机的链接
    AVCaptureConnection *connection = nil;
    for (AVCaptureConnection *tempConnection in self.imageOutput.connections) {
        for (AVCaptureInputPort *port in [tempConnection inputPorts]) {
            if ([[port mediaType] isEqualToString:AVMediaTypeVideo]) {
                connection = tempConnection;
                break;
            }
        }
        if (connection) {
            break;
        }
    }
    
    //保存图片
    [self.imageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        
        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage *image = [[UIImage alloc] initWithData:imageData];

        [self p_presentEditViewController:image];
        
    }];
}


//切换摄像头事件
- (void)swithCameraButtonMethod{
  
    AVCaptureDeviceInput *currentInput = [self getVideoInput];
    if (currentInput) {
        AVCaptureDevicePosition newPosition = AVCaptureDevicePositionFront;
        if (currentInput.device.position == AVCaptureDevicePositionFront) {
            newPosition = AVCaptureDevicePositionBack;
        }
        
        AVCaptureDevice *newDevice = nil;
        NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
        for (AVCaptureDevice *device in devices) {
            if ([device position] == newPosition) {
                newDevice = device;
                break;
            }
        }
        NSError *error;
        AVCaptureDeviceInput *newInput = [AVCaptureDeviceInput deviceInputWithDevice:newDevice error:&error];
        [self.session beginConfiguration];
        [self.session removeInput:currentInput];
        [self.session addInput:newInput];
        [self.session commitConfiguration];
        
    }
    
    
}

// 获取相机 input
- (AVCaptureDeviceInput *)getVideoInput {
    
    for (AVCaptureDeviceInput *input in self.session.inputs) {
        if ([input.device hasMediaType:AVMediaTypeVideo]) {
            return input;
        }
    }
    
    return nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (AVCaptureSession *)session{
    if (!_session) {
        _session = [[AVCaptureSession alloc] init];
    }
    return _session;
}
- (UIView *)preview{
    if (!_preview) {
        _preview = [[UIView alloc] initWithFrame:self.view.bounds];
        _preview.layer.backgroundColor = [UIColor blackColor].CGColor;
        
    }
    return _preview;
}

@end
